package com.shine.icis.ts.client;

import org.apache.axiom.om.OMAbstractFactory;
import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.OMFactory;
import org.apache.axiom.om.OMNamespace;
import org.apache.axis2.AxisFault;
import org.apache.axis2.addressing.EndpointReference;
import org.apache.axis2.client.Options;
import org.apache.axis2.client.ServiceClient;

import com.shine.icis.exception.ICISException;

public class TaskServerClient {
	private boolean enable;
	private String serviceUrl;
	public TaskServerClient(String serviceUrl) {
		this.enable = serviceUrl != null && !serviceUrl.trim().equals("");
		this.serviceUrl = serviceUrl;
	}
	
	public boolean restartTaskServer() throws Exception {
		if (!enable) {
			return false;
		}
//		TaskServerToolService ser = new TaskServerToolService(TaskServerToolService.getWsdlLocation(wsdlUrl));
//		TaskServerTool tsTool = ser.getTaskServerToolPort();
//		
//		tsTool.restart();
		
		/*
		 * 公司JBOSS版本在JDK1.6中使用WebSerice有实突，JDK1.6中相亲实现代码过新。
		 * 所以改用axis2来调用
		 */
        EndpointReference endpointReference = new EndpointReference(serviceUrl);
        //创建一个OMFactory，下面的namespace、方法与参数均需由它创建
        OMFactory factory = OMAbstractFactory.getOMFactory();
        //对应于@WebService(targetNamespace = "...")
        OMNamespace namespace = factory.createOMNamespace("http://ts.icis.shine.com/", "xsd");

        //下面创建一个method对象，"restart"为方法名
        OMElement method = factory.createOMElement("restart", namespace);
        
        Options options = new Options();
        options.setAction("http://ts.icis.shine.com/");  //此处对应于@WebMethod(action = "...")
        options.setTo(endpointReference);

        try {
	        ServiceClient sender = new ServiceClient();
	        sender.setOptions(options);
	
	        //发送并得到结果，至此，调用成功，并得到了结果
	        OMElement result = sender.sendReceive(method);
	        
	        sender.cleanupTransport();
	        String resultStr = result.getFirstElement().getText();
	        return Boolean.parseBoolean(resultStr);
        } catch (AxisFault e) {
        	e.printStackTrace();
        	throw new ICISException("连接失败，确保TASKSERVER服务器已启动。");
        }
	}
	
	public boolean isEnable() {
		return enable;
	}
	public void setEnable(boolean enable) {
		this.enable = enable;
	}
	public String getServiceUrl() {
		return serviceUrl;
	}
	public void setServiceUrl(String serviceUrl) {
		this.serviceUrl = serviceUrl;
	}
	
}
